<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/10/18
 * Time: 18:19
 */
require_once('env.php');
require_once('functions.php');

$data = $_REQUEST;


if (!$data['user_name'] || !$data['phone'] || !$data['email'] || !$data['addr']) {
    die(json_encode(array("code" => 1001, "msg" => "提交的數據都不能為空")));
}


$pattern = "/^[\x{4e00}-\x{9fa5}]{2,4}$/u";
if (!preg_match($pattern, $data['user_name'])) {
    die(json_encode(array("code" => 1004, "msg" => "姓名為中文且須在2-4位")));
}

//验证台湾电话是否合法
$pattern = "/^[0]\d{9}$/";
if (!preg_match($pattern, $data['phone'])) {
    die(json_encode(array("code" => 1002, "msg" => "電話號碼非法")));
}

//验证邮箱格式
$pattern = "/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
if (!preg_match($pattern, $data['email'])) {
    die(json_encode(array("code" => 1003, "msg" => "郵箱格式不正確")));
}

$lastId = lastedInsertId();
$order_sn = "SN_" . $lastId;
$input_data = array("product_id" => $data['product_id'], "order_sn" => $order_sn, "num" => 0, "user_name" => $data['user_name'], "phone" => $data['phone'], "email" => $data['email'], "addr" => $data['addr'], "add_date" => date('Y-m-d H:i:s'));
$ret = addUserInfo($input_data);

if ($ret) {
    $product = getProductById($data['product_id']);
    //更新產品已售數量
    $update_data = array("products_sales_num" => $product['products_sales_num'] + 1);
    updateProducts($data['product_id'], $update_data);
    $send_data = array("to_email" => $data['email'], "order_sn" => $order_sn, "product_id" => $data['product_id'], "createtime" => time());
    saveEmailData($send_data);//先保存 后端异步去发
    die(json_encode(array("code" => 0, "msg" => "申請成功，郵件已經發至您的郵箱，請查收","href"=>"success.php")));
} else {
    die(json_encode(array("code" => "-1", "msg" => "申請失敗","href"=>"error.php")));
}
